# -*- coding: latin-1 -*-

import sys
import cPickle
import base64
import datetime

from PyQt4 import QtCore

import Code.Util as Util

import Code.QT.FormLayout as FormLayout
import Code.QT.Iconos as Iconos

#=========================================================================================
def listaMoscasRecuperar( configuracion ) :
    lista = Util.recuperaVar( configuracion.ficheroMoscas )
    if lista is None :
        lista = []
    return lista
#=========================================================================================
def listaMoscasGrabar( configuracion, lista ) :
    Util.guardaVar( configuracion.ficheroMoscas, lista )

#=========================================================================================
def nuevaMosca( ventana, configuracion ) :
    # Datos generales
    liGen = [(None,None)]

    ## Nombre
    liGen.append( ( _( "Kibitzer" ) + " :", "" ) )

    ## Motor
    config = FormLayout.Combobox( _( "Engine" ), configuracion.comboMotoresCompleto() )
    liGen.append( ( config, "stockfish" ) )

    ## Tipo
    liTipos = [ "S", ( "S", _("Analyzes response to the current position") ), ( "C", _("Analyze threats")), ( "J", _("Displays and analyzes possible moves"))]
    liGen.append( (_( "Type"), liTipos) )

    # Editamos
    resultado = FormLayout.fedit( liGen, title= _( "New" ), parent = ventana, anchoMinimo = 460, icon = Iconos.Mosca() )

    if resultado :
        accion, resp = resultado

        mosca = resp[0]
        motor = resp[1]
        tipo = resp[2]
        if not mosca :
            mosca = motor

        d = datetime.datetime.now()
        id = "MOS"+d.isoformat()[2:].strip("0").replace("-","").replace("T","").replace(":","").replace(".","")
        fvideo = configuracion.plantillaVideo%id

        dic = { "NOMBRE":mosca, "MOTOR":motor, "TIPO":tipo, "FVIDEO":fvideo }

        liMoscas = listaMoscasRecuperar( configuracion )
        liMoscas.append( dic )

        listaMoscasGrabar( configuracion, liMoscas )

        return liMoscas
    else :
        return None

#=========================================================================================
class Orden :
    def __init__( self ) :
        self.clave = ""
        self.titulo = ""
        self.dv = {}

    def ponVar( self, nombre, valor ) :
        self.dv[nombre] = valor

    def bloqueEnvio( self ) :
        texto = base64.encodestring(cPickle.dumps(self.dv))
        prologo = "1234567890:"
        return "%s%s%05d%s"%(prologo,self.clave, len(texto), texto )

    def dicTexto( self, texto ) :
        if texto :
            self.dv = cPickle.loads( base64.decodestring(texto) )
        else :
            self.dv = {}
        return self.dv

    def __str__( self) :
        return "%s-%s-%s"%(self.clave,self.titulo, str(self.dv) )

# ===========================================================================================================================
class XMosca(QtCore.QProcess):

    CONFIGURACION = "C"
    FEN = "F"
    TERMINAR = "T"

    def __init__( self, gestor, mosca ) :

        # Lanzamos ya el motor
        QtCore.QProcess.__init__( self )

        if sys.argv[0][-3:].lower() == "pyw" :
            exe = "pythonw.exe"
            arg = ["lucas.pyw", "-mosca" ]
        else :
            exe = "lucas.exe"
            arg = ["-mosca"]

        # self.setWorkingDirectory ( "." )
        self.start( exe, arg, mode = QtCore.QIODevice.Unbuffered | QtCore.QIODevice.ReadWrite )
        self.waitForStarted()

        motor = mosca["MOTOR"]
        configMotor = gestor.configuracion.buscaRivalExt( motor )

        orden = Orden()
        orden.clave = self.CONFIGURACION
        orden.dv["CONFIGURACION"] = gestor.configuracion
        orden.dv["TITULO"] = mosca["NOMBRE"]
        orden.dv["FVIDEO"] = mosca["FVIDEO"]
        orden.dv["TIPO"] = mosca["TIPO"]
        orden.dv["CONFIG_MOTOR"] = configMotor

        self.escribe( orden )

    # -----------------------------------------------------------------------------------------
    def escribe( self, orden ) :
        self.write( orden.bloqueEnvio() )

    # -----------------------------------------------------------------------------------------
    def siActiva( self ) :
        return self.state() != self.NotRunning

    # -----------------------------------------------------------------------------------------
    def ponFen( self, fen ) :
        orden = Orden()
        orden.clave = self.FEN
        orden.dv["FEN"] = fen
        self.escribe( orden )

    # -----------------------------------------------------------------------------------------
    def terminar( self ) :
        try :
            orden = Orden()
            orden.clave = self.TERMINAR
            self.escribe( orden )
            self.close()
        except :
            pass

